﻿//----------------------------------------------
//            NGUI: Next-Gen UI kit
// Copyright © 2011-2012 Tasharen Entertainment
//----------------------------------------------

using UnityEngine;
using System.Collections;

/// <summary>
/// Allows dragging of the specified target object by mouse or touch
/// </summary>

[AddComponentMenu("NGUI/Interaction/Drag Window")]
public class UIDragWindow : MonoBehaviour
{
	public Transform target;
	static int canDragBoder = 20;
	bool isDragging = false;
	
	void Start()
	{
		if(target == null)
			target = transform;

		UpdateDragPanel();
	}
	
	public void UpdateDragPanel()
	{
//		UIPanel mPanel = NGUITools.FindInParents<UIPanel>(target.gameObject);
//		if (mPanel != null) 
//		{
//			Vector3 offset = mPanel.cachedTransform.localPosition;
//			if(mPanel.clipping == UIDrawCall.Clipping.None)
//				mPanel.clipping = UIDrawCall.Clipping.AlphaClip;
//			
//			mPanel.clipRange = new Vector4(-offset.x, -offset.y, Screen.width, Screen.height);
//		}
		
		UIPanel mPanel = NGUITools.FindInParents<UIPanel>(target.gameObject);
		if (mPanel != null) 
		{			
			mPanel.clipping = UIDrawCall.Clipping.None;
		}
	}

	/// <summary>
	/// Drag the object
	/// </summary>
	void OnDrag (Vector2 delta)
	{
		isDragging = true;
		if(target != null)
		{
			target.localPosition += new Vector3(delta.x, delta.y , 0);
			
			float revertX = 0;
			float revertY = 0;
			if(rect.x + rect.width < canDragBoder)
			{
				revertX = canDragBoder - (rect.x + rect.width );
			}
			
			if(rect.x > Screen.width - canDragBoder)
			{
				revertX = Screen.width - canDragBoder - rect.x ;
			}
			
			if(rect.y + rect.height < canDragBoder)
			{
				revertY = canDragBoder - (rect.y + rect.height);
			}
			
			if(rect.y > Screen.height - canDragBoder)
			{
				revertY = Screen.height - canDragBoder - rect.y;
			}
			
			target.localPosition += new Vector3(revertX, -revertY, 0);	
		}
	}
	
	//
	void OnPress (bool isPressed)
	{
		if(!isPressed)
		{
			if(isDragging)
				UIManager.MakeUINodePerfectPixelPosition(target, false);
			
			isDragging = false;
		}
	}
	
	//当前对象Rect
	public Rect rect
	{
		get
		{
			Vector3 size = UIManager.GetControlSize(target.gameObject);
			Vector3 center = UIManager.GetControlCenterScreenPosition(target.gameObject);
			return new Rect(center.x - size.x / 2, center.y - size.y / 2, size.x, size.y);
		}
	}
}